<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id="myCanvas" width="1080" height="630" style="border: 1px solid;"></canvas>
</body>

</html>
<script>

    const ctx = myCanvas.getContext('2d');

    let p1 = [50, 50];
    let p2 = [400, 50];

    function getVctLen([x, y]) {
        return Math.sqrt(x * x + y * y);
    };

    /**
* 根据点在向量上的比例计算点坐标, [xO, yO]为起点，[xVct, yVct]为向量，k 为该点在向量方向上的长度
* 获取
*/
    function getPntInVct([xO, yO], [xVct, yVct], k) {
        let lenVct = getVctLen([xVct, yVct]);  // 获取向量长度
        let stdVct;
        if (lenVct === 0) {
            stdVct = [0, 0];
        } else {
            stdVct = [xVct / lenVct, yVct / lenVct];   // 单位向量
        }
        return [xO + k * stdVct[0], yO + k * stdVct[1]];
    };

    let vct = [p2[0] - p1[0], p2[1] - p1[1]];  // 终点减起点,那向量的方向是起点指向终点

    var len = .5;
    function draw() {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

        let p3 = getPntInVct(p1, vct, getVctLen(vct) * len);

        ctx.font = "18px serif"
        ctx.lineWidth = 5;
        ctx.strokeStyle = "red";
        ctx.moveTo(p1[0], p1[1]);
        ctx.lineTo(p2[0], p2[1]);
        ctx.stroke();
        ctx.fillText("向量1", p2[0], p2[1])

        ctx.beginPath();
        ctx.fillStyle = "blue";
        ctx.arc(p3[0], p3[1], 5, 0, 2 * Math.PI);
        ctx.fill();
        ctx.fillText(len+"取点", p3[0] + 10, p3[1]-10);
    }

    setInterval(draw, 0);

    window.addEventListener("keydown", (e) => {
        if (e.keyCode == 38) {
            len += .1;
        }
        if (e.keyCode == 40) {
            len -= .1;
        }
    })

</script>
<style>
    canvas {
        border: 1px solid #ccc;
        background-image: linear-gradient(90deg,
                #ffffb8 1%,
                rgba(0, 0, 0, 0) 5%),
            linear-gradient(#ffffb8 1%, rgba(0, 0, 0, 0) 5%);
        background-size: 28px 28px;
    }
</style>